package cn.edu.ldu.views.login;

/**
 *
 * @author DYZ
 */
import cn.edu.ldu.entity.FriendsEntity;
import cn.edu.ldu.entity.UserEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import cn.edu.ldu.util.Ports;
import cn.edu.ldu.util.Translate;
import cn.edu.ldu.views.main.MainUI;
import com.alibaba.fastjson.JSON;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.*;

/**
 *
 * @author DYZ
 */
public class LoginUI extends javax.swing.JFrame {
    LoginUI loginUI;
    /**
     * Creates new form LoginUI
     */

    public LoginUI() {
        super();
        loginUI = this;
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        contentPanel = new javax.swing.JPanel();
        loginPanel = new javax.swing.JPanel();
        labLogo = new javax.swing.JLabel();
        labUserId = new javax.swing.JLabel();
        txtUserId1 = new javax.swing.JTextField();
        labPassword = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        btnRegister = new javax.swing.JButton();
        btnEditPass = new javax.swing.JButton();
        btnLogin = new javax.swing.JButton();


        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBounds(new java.awt.Rectangle(0, 0, 600, 600));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocation(new java.awt.Point(90, 90));
        setMaximumSize(new java.awt.Dimension(900, 900));
        setMinimumSize(new java.awt.Dimension(600, 600));
        setPreferredSize(new java.awt.Dimension(650, 500));
        setResizable(false);

        contentPanel.setPreferredSize(new java.awt.Dimension(Consts.L_CONTENT_WIDTH, Consts.L_CONTENT_HEIGHT_NORMAL));

        javax.swing.GroupLayout contentPanelLayout = new javax.swing.GroupLayout(contentPanel);
        contentPanel.setLayout(null);
        contentPanelLayout.setHorizontalGroup(
                contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 583, Short.MAX_VALUE)
        );
        contentPanelLayout.setVerticalGroup(
                contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 150, Short.MAX_VALUE)
        );

        getContentPane().add(contentPanel, BorderLayout.CENTER);

        loginPanel.setMaximumSize(new java.awt.Dimension(600, 600));

        labLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/BG.jpg"))); // NOI18N

        labUserId.setText("账号：");
        txtUserId1.setText("786569952");

        labPassword.setText("密码：");
        txtPassword.setText("12345678");

        btnRegister.setText("注册账户");
        btnRegister.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnMouseClicked(evt, new RegisterUI());
            }
        });

        btnEditPass.setText("修改密码");
        btnEditPass.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e) {
                btnMouseClicked(e, new EditPassUI());
            }
        });

        btnLogin.setText("确定登录");
        btnLogin.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e) {
                btnLoginClicked(e);
            }
        });

        javax.swing.GroupLayout loginPanelLayout = new javax.swing.GroupLayout(loginPanel);
        loginPanel.setLayout(loginPanelLayout);
        loginPanelLayout.setHorizontalGroup(
                loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loginPanelLayout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loginPanelLayout.createSequentialGroup()
                                                        .addComponent(labLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 555, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addContainerGap())
                                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loginPanelLayout.createSequentialGroup()
                                                        .addComponent(labUserId, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addComponent(txtUserId1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGap(101, 101, 101)))
                                        .addGroup(loginPanelLayout.createSequentialGroup()
                                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(loginPanelLayout.createSequentialGroup()
                                                                .addGap(79, 79, 79)
                                                                .addComponent(labPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addGroup(loginPanelLayout.createSequentialGroup()
                                                                .addGap(30, 30, 30)
                                                                .addComponent(btnRegister)))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                        .addGroup(loginPanelLayout.createSequentialGroup()
                                                                .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addGap(101, 101, 101))
                                                        .addGroup(loginPanelLayout.createSequentialGroup()

                                                                .addGap(41, 41, 41)
                                                                .addComponent(btnEditPass)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                .addComponent(btnLogin)
                                                                .addGap(36, 36, 36))))))
        );
        loginPanelLayout.setVerticalGroup(
                loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(loginPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(labLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(labUserId, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(txtUserId1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(47, 47, 47)
                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(labPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(52, 52, 52)
                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnRegister)
                                        .addComponent(btnEditPass)
                                        .addComponent(btnLogin))
                                .addGap(23, 23, 23))
        );

        getContentPane().add(loginPanel, BorderLayout.NORTH);

        pack();
    }// </editor-fold>

    /*
    **注册按钮
     */
    private void btnMouseClicked(java.awt.event.MouseEvent evt, JPanel jPanel) {
        // TODO add your handling code here:


        //如果没有
        if(contentPanel.getComponentCount()==0){
            this.setSize(Consts.L_LOGIN_WIDTH, Consts.L_LOGIN_HEIGHT_OPEN);
            contentPanel.setSize(Consts.L_CONTENT_WIDTH, Consts.L_CONTENT_HEIGHT_OPEN);
            contentPanel.add(jPanel);
            contentPanel.updateUI();
            contentPanel.repaint();
        }else {
            contentPanel.removeAll();
            contentPanel.setSize(Consts.L_CONTENT_WIDTH,Consts.L_CONTENT_HEIGHT_NORMAL);
            this.setSize(Consts.L_LOGIN_WIDTH,Consts.L_LOGIN_HEIGHT_NORMAL);
            contentPanel.updateUI();
            contentPanel.repaint();
        }
    }

    /**
     * 登录按钮
     */
    private void btnLoginClicked(java.awt.event.MouseEvent evt){

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Long id = Long.parseLong(txtUserId1.getText().trim()) ;
                    String pass = txtPassword.getText().trim();
                    if(id.equals("")||pass.equals("")){
                        JOptionPane.showMessageDialog(null,"账号或密码为空","错误提示",JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    //服务器
                    InetAddress remoteAddr = null;
                    try {
                        remoteAddr = InetAddress.getByName(Consts.ipv4);
                        //创建UDP套件字
                        DatagramSocket clientSocket = Ports.getCommon();
//                        clientSocket.setSoTimeout(10000);
                        //构造用户登录信息
                        Protocol protocol = new Protocol();
                        protocol.setKey("Login");
                        UserEntity ue = new UserEntity();
                        ue.setId(id);
                        ue.setPassword(pass);

                        //转字符
                        protocol.setData(JSON.toJSONString(ue));

                        byte[] data = Translate.ObjectToByte(protocol);
                        //定义登录报文
                        DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);
                        //send views datagram
                        clientSocket.send(packet);
                        L.OK(packet,LoginUI.class);
                        while (true){
                            //从服务器得到令牌
                            byte[] backData = new byte[8096];
                            DatagramPacket backPacket = new DatagramPacket(backData,backData.length,remoteAddr,Consts.port);

                            try {
                                clientSocket.receive(backPacket);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            L.OK(backPacket,LoginUI.class);

                            Protocol pro = (Protocol)Translate.ByteToObject(backPacket.getData());

                            //解决视图结果
                            try{
                                Class cls = Class.forName("cn.edu.ldu.protocol."+pro.getKey());
                                //protocol.loginsucces
                                Constructor con = cls.getConstructor(Protocol.class);
                                con.newInstance(pro);
                                loginUI.dispose();
                            } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, "请求超时","错误",JOptionPane.ERROR_MESSAGE);
                    }
                }
            }).start();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try
        {
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
        }
        catch(Exception e)
        {
            //TODO exception
            System.out.println("加载炫彩皮肤失败！");
        }
        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                LoginUI dialog = new LoginUI();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnEditPass;
    private javax.swing.JButton btnLogin;
    private javax.swing.JButton btnRegister;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JLabel labLogo;
    private javax.swing.JLabel labPassword;
    private javax.swing.JLabel labUserId;
    private javax.swing.JPanel loginPanel;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtUserId1;
    // End of variables declaration
}